﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ADDDF.Infrastructure;

namespace ADDDF.Infrastructure.Test
{
    public class PartyRepository : RepositoryBase<PartyEntity>, IPartyRepository
    {
        private static int s_nextKey;
        private static List<PartyEntity> s_items;

        static PartyRepository()
        {
            PartyRepository.Reset(100);
        }

        public static void Reset(int nextKey)
        {
            s_nextKey = nextKey;
            s_items = new List<PartyEntity>();
        }

        public override void Add(PartyEntity item)
        {
            int key = s_nextKey++;

            PartyEntity newOne = new PartyEntity(key, item.Name);

            s_items.Add(newOne);

            base.SetEntityKey(item, key);
        }

        public override void Change(PartyEntity item)
        {
            PartyEntity existing = s_items.SingleOrDefault(x => x.Key.Equals(item.Key));

            if (existing == null)
                throw new InvalidOperationException("Existing party is missing");

            s_items.Remove(existing);

            PartyEntity clone = new PartyEntity(item.Key, item.Name);

            s_items.Add(clone);
        }

        public override void Remove(PartyEntity item)
        {
            PartyEntity existing = s_items.SingleOrDefault(x => x.Key.Equals(item.Key));

            if (existing == null)
                throw new InvalidOperationException("Existing party is missing");

            s_items.Remove(existing);
        }
                
        public override PartyEntity FindByKey(object key)
        {
            // Cannot compare x.Key and key with ==.
            // return _parties.SingleOrDefault(x => x.Key == key); // doesn't work

            // Equals can work
            //return _parties.SingleOrDefault(x => x.Key.Equals(key)); // works

            // If not using Equals then use cast like below
            return s_items.SingleOrDefault(x => (int)x.Key == (int)key); // works
        }

        public override IEnumerable<PartyEntity> FindAll()
        {
            List<PartyEntity> list = new List<PartyEntity>();
            foreach (PartyEntity p in s_items)
            {
                list.Add(new PartyEntity(p.Key, p.Name));
            }
            return list;
        }

        public IList<PartyEntity> FindByName(string name)
        {
            List<PartyEntity> matches = s_items.Where(x => x.Name == name).ToList();
            List<PartyEntity> list = new List<PartyEntity>();
            foreach (PartyEntity p in matches)
            {
                list.Add(new PartyEntity(p.Key, p.Name));
            }
            return list;
        }
    }
}
